package com.noble.glamour.ui.agora.act.vfloat;

import android.content.Context;
import android.os.SystemClock;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.Chronometer;
import android.widget.FrameLayout;
import android.widget.ImageView;

import com.noble.glamour.ui.agora.RtcUIShow;
import com.noble.library.log.PToast;
import com.noble.library.observe.MsgMgr;
import com.noble.library.observe.MsgType;
import com.noble.library.observe.PObserver;
import com.noble.library.view.CustomFrameLayout;
import com.noble.glamour.R;
import com.noble.glamour.module.logic.application.App;
import com.noble.glamour.module.logic.application.ModuleMgr;
import com.noble.glamour.module.logic.request.HttpResponse;
import com.noble.glamour.module.logic.request.RequestComplete;
import com.noble.glamour.ui.agora.act.bean.Accept;
import com.noble.glamour.ui.agora.act.bean.ChatStatus;
import com.noble.glamour.ui.agora.manager.RtcMessageMgr;
import com.noble.glamour.ui.agora.model.AgoraConstant;
import com.noble.glamour.ui.agora.model.EngineConfig;
import com.noble.glamour.ui.agora.util.RtcJointChannel;
import com.noble.glamour.ui.agora.util.RtcSubUtil;
import com.noble.glamour.ui.agora.util.RtcTimerUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 音视频悬浮窗管理器
 * <p>
 * Created by Su on 2017/7/12.
 */
public class RtcFloatManager implements View.OnTouchListener, PObserver {
    private Context mContext;
    private RtcFloatListener mFloatingViewListener; // 悬浮窗监听器
    private final WindowManager mWindowManager;
    private List<RtcFloatView> mFloatingViewList;  // 悬浮窗集合

    private CustomFrameLayout customFrameLayout;
    private FrameLayout videoContainer;
    private ImageView chatType;
    private Chronometer ch;

    public RtcFloatManager(Context context, RtcFloatListener floatingViewListener) {
        this.mContext = context;
        this.mFloatingViewListener = floatingViewListener;
        this.mWindowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        this.mFloatingViewList = new ArrayList<>();

        addListener();
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        return false;
    }

    /**
     * 添加悬浮窗
     */
    public void addFloatingView() {
        // 悬浮窗配置信息
        DisplayMetrics dm = new DisplayMetrics();
        mWindowManager.getDefaultDisplay().getMetrics(dm);
        RtcFloatManager.Configs configs = new RtcFloatManager.Configs();
        configs.overMargin = -(int) (8 * dm.density);
        configs.floatingViewX = dm.widthPixels;
        configs.floatingViewY = (int) (8 * dm.density);

        // 创建悬浮窗
        RtcFloatView floatingView = new RtcFloatView(this.mContext, configs.floatingViewX, configs.floatingViewY);
        floatingView.setOnTouchListener(this);
        floatingView.setOverMargin(configs.overMargin);
        floatingView.setMoveDirection(configs.moveDirection);
        floatingView.setAnimateInitialMove(configs.animateInitialMove);  // 移动是否带动画

        // 悬浮窗视图组件
        View view = initFloatView();

        // 设置悬浮窗的大小
        FrameLayout.LayoutParams targetParams = new FrameLayout.LayoutParams(configs.floatingViewWidth, configs.floatingViewHeight);
        view.setLayoutParams(targetParams);
        floatingView.addView(view);

        // 添加悬浮窗到集合
        this.mFloatingViewList.add(floatingView);

        // 添加悬浮窗
        this.mWindowManager.addView(floatingView, floatingView.getWindowLayoutParams());
    }

    /**
     * 同步操作问题
     */
    private void addListener() {
        // 通话失效
        if (RtcMessageMgr.getInstance().leaveChat()) {
            stopFloat();
            PToast.showLong(App.context.getString(R.string.chat_tips_user_hangup));
            return;
        }

        // 已收到对方同意通话消息
        if (RtcMessageMgr.getInstance().inChat()) {
            RtcJointChannel.getInstance().joinChannelPrepare(false);
            if (config().mChatType == AgoraConstant.RTC_CHAT_VIDEO) {
                RtcUIShow.showRtcVideoAct(App.activity);
            } else {
                RtcUIShow.showRtcVoiceAct(App.activity);
            }
            ModuleMgr.getRtcEnginMgr().justStopRtcFloatService();
            return;
        }
        MsgMgr.getInstance().attach(this);
    }

    /**
     * 初始化悬浮窗视图组件
     */
    private View initFloatView() {
        View view = LayoutInflater.from(App.getContext()).inflate(R.layout.v1_chat_float_view, null, false);
        customFrameLayout = (CustomFrameLayout) view.findViewById(R.id.call_frameLayout);
        chatType = (ImageView) view.findViewById(R.id.iv_chat_type);
        ch = (Chronometer) view.findViewById(R.id.call_time_ch);
        videoContainer = (FrameLayout) view.findViewById(R.id.video_float);
        customFrameLayout.show(R.id.call_float_root_view);
        if (!config().mJoinStatus) {
            waitStatus();
        } else {
            if (config().mChatType == AgoraConstant.RTC_CHAT_VOICE) { // 音频
                ch.setBase(SystemClock.elapsedRealtime() - ModuleMgr.getRtcEnginMgr().getEngineConfig().millisPass);
                ch.start();
            } else {
                setSurfaceView();
            }
        }
        if (config().mChatType == AgoraConstant.RTC_CHAT_VOICE) {
            chatType.setImageResource(R.drawable.f1_user_chat_voice);
        }

        view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 关闭悬浮窗
                ModuleMgr.getRtcEnginMgr().stopRtcFloatService();
            }
        });
        return view;
    }

    /**
     * 接听等待状态
     */
    private void waitStatus() {
        if (config().mInviteType == AgoraConstant.RTC_CHAT_BEINVITE) {
            ch.setText(App.context.getString(R.string.chat_wait_connect_beInvite));
            return;
        }

        if (!ModuleMgr.getCenterMgr().getMyInfo().isMan()) {
            ch.setText(App.context.getString(R.string.chat_wait_connect_female));
        } else {
            ch.setText(App.context.getString(R.string.chat_wait_connect_man));
        }
    }

    private void setSurfaceView() {
        customFrameLayout.show(R.id.video_float);
        videoContainer.removeAllViews();
        if (ModuleMgr.getRtcEnginMgr().getEngineConfig().mOpenCamera) {
            RtcJointChannel.getInstance().removeRemoteView();
            videoContainer.addView(RtcJointChannel.getInstance().getRemoteSurfaceV());
            return;
        }
        RtcJointChannel.getInstance().removeLocalView();
        videoContainer.addView(RtcJointChannel.getInstance().getLocalSurfaceV());
    }

    private void stopFloat() {
        ModuleMgr.getRtcEnginMgr().justStopRtcFloatService();
        ModuleMgr.getRtcEnginMgr().releaseAll();
    }

    @Override
    public void onMessage(String key, Object value) {
        switch (key) {
            case MsgType.MT_Rtc_Chat_Status:
                Map<String, Object> data = (Map<String, Object>) value;
                switch ((int) data.get("type")) {
                    case 2:     // 同意加入
                        RtcJointChannel.getInstance().joinChannelPrepare(false);
                        if (config().mChatType == AgoraConstant.RTC_CHAT_VIDEO) { // 视频聊天
                            RtcUIShow.showRtcVideoAct(App.activity);
                        } else {
                            RtcUIShow.showRtcVoiceAct(App.activity);
                        }
                        ModuleMgr.getRtcEnginMgr().justStopRtcFloatService();
                        break;

                    case 3:     // 拒絕加入
                    case 4:     // 挂断
                        stopFloat();
                        break;

                    default:
                        break;
                }
                break;

            case MsgType.MT_Rtc_Chat_Connect_Suc:
                ch.start();
                break;

            case MsgType.MT_Rtc_Check_Video_Chat:
                ChatStatus chatStatus = (ChatStatus) value;
                RtcTimerUtil.getInstance().startStatisTipsTime(chatStatus.getTimeLeft() * 1000);

                if (chatStatus.getTimeLeft() <= AgoraConstant.CHAT_COST_PROMPT) {  // 当剩余倒计时不足60s时关闭轮询
                    RtcSubUtil.getInstance().stopVideoChatTime();
                }
                break;

            case MsgType.MT_Rtc_Chat_Close_Msg:
                ModuleMgr.getRtcEnginMgr().justStopRtcFloatService();
                ModuleMgr.getRtcEnginMgr().releaseAll();
                break;

            case MsgType.MT_Rtc_Chat_Count_Finish_Msg: // 余额倒计时已到
                ModuleMgr.getRtcEnginMgr().justStopRtcFloatService();
                ModuleMgr.getRtcEnginMgr().releaseAll();
                break;

            case MsgType.MT_Rtc_Group_Chat_Msg:
                handleGroupInvite();
                break;

            case MsgType.MT_Rtc_Chat_Remote_Status:  // 远端视频开启状态
                if ((boolean) value) {  // 远端关闭
                    setLocalView();
                    return;
                }
                // 远端开启
                setRemoteView();
                break;

            case MsgType.MT_Rtc_Chat_Video_Remote: // 首次绑定远端
                setRemoteView();
                break;
        }
    }

    private void setLocalView() {
        RtcJointChannel.getInstance().removeLocalView();
        videoContainer.removeAllViews();
        videoContainer.addView(RtcJointChannel.getInstance().getLocalSurfaceV());
    }

    private void setRemoteView() {
        RtcJointChannel.getInstance().removeRemoteView();
        videoContainer.removeAllViews();
        videoContainer.addView(RtcJointChannel.getInstance().getRemoteSurfaceV());
    }

    private EngineConfig config() {
        return ModuleMgr.getRtcEnginMgr().getEngineConfig();
    }

    /**
     * 女性用户： 群邀有男用户接受邀请处理
     */
    private void handleGroupInvite() {
        ModuleMgr.getRtcChatMgr().reqAcceptVideoChat(config().mVcid, new RequestComplete() {
            @Override
            public void onRequestComplete(HttpResponse response) {
                if (response.isOk()) {
                    Accept accept = (Accept) response.getBaseData();
                    config().mChannelKey = accept.getChannelKey();
                    config().msgVer = accept.getMsgVer();
                    startChat();
                    return;
                }
                PToast.showShort(response.getMsg() == null ? App.context.getString(R.string.chat_join_fail_tips) : response.getMsg());
                ModuleMgr.getRtcEnginMgr().reqVCGroupCancel(config().mInviteID, null);
                ModuleMgr.getRtcEnginMgr().justStopRtcFloatService();
            }
        });
    }

    private void startChat() {
        RtcJointChannel.getInstance().joinChannelPrepare(true);
        if (config().mChatType == AgoraConstant.RTC_CHAT_VIDEO)
            RtcUIShow.showRtcVideoAct(App.activity);
        else
            RtcUIShow.showRtcVoiceAct(App.activity);
        ModuleMgr.getRtcEnginMgr().justStopRtcFloatService();
    }

    /**
     * 移除悬浮窗
     *
     * @param floatingView
     */
    private void removeFloatingView(RtcFloatView floatingView) {
        int matchIndex = this.mFloatingViewList.indexOf(floatingView);
        if (matchIndex != -1) {
            this.mWindowManager.removeViewImmediate(floatingView);
            this.mFloatingViewList.remove(matchIndex);
        }
        if (this.mFloatingViewList.isEmpty()) {
            if (this.mFloatingViewListener != null) {
                this.mFloatingViewListener.onFinishFloatView();
            }
        }
    }

    /**
     * 移除所有的悬浮窗
     */
    public void removeAllFloatingView() {
        MsgMgr.getInstance().detach(this);

        if (this.mFloatingViewList != null) {
            for (RtcFloatView floatingView : mFloatingViewList) {
                this.mWindowManager.removeViewImmediate(floatingView);
            }
            this.mFloatingViewList.clear();
        }
        ch.stop();
        ch = null;
    }

    /**
     * 悬浮窗的配置信息
     */
    public static class Configs {
        /**
         * 悬浮窗的x坐标
         */
        public int floatingViewX;

        /**
         * 悬浮窗的y坐标
         */
        public int floatingViewY;

        /**
         * 悬浮窗的宽度（单位：px）
         */
        public int floatingViewWidth;

        /**
         * 悬浮窗的高度（单位：px）
         */
        public int floatingViewHeight;

        /**
         * 悬浮窗边缘的外边距
         */
        public int overMargin;

        /**
         * 悬浮窗移动方向
         */
        @RtcFloatView.MoveDirection
        public int moveDirection;

        /**
         * 悬浮窗移动时是否带动画
         */
        public boolean animateInitialMove;

        public Configs() {
            this.floatingViewX = RtcFloatView.DEFAULT_X;
            this.floatingViewY = RtcFloatView.DEFAULT_Y;
            this.floatingViewWidth = RtcFloatView.DEFAULT_WIDTH;
            this.floatingViewHeight = RtcFloatView.DEFAULT_HEIGHT;
            this.overMargin = 0;
            this.moveDirection = RtcFloatView.MOVE_DIRECTION_DEFAULT;
            this.animateInitialMove = true;
        }
    }
}
